package db4oClass.appClass;

import general.appClass.SystemInfo;
import general.dbClass.DBCategory;
import general.dbClass.DBKeyword;
import general.dbClass.DBPicInfo;
import general.dbClass.DBThumbInfo;
import general.dbClass.SearchTerm;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db4o.ObjectContainer;
import com.db4o.query.Query;

import db4oClass.daoClass.Db4oDaoGet;

/**
 * Servlet implementation class db4oSearchApp
 */
@WebServlet("/db4oSearchApp")
public class db4oSearchApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static ArrayList<DBThumbInfo> lastSearchResult = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public db4oSearchApp() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-Cache");
		response.setHeader("Cache-Control", "No-Cache");
		response.setDateHeader("Expires", 0);

		//System Information Manage Class
		ObjectContainer container = SystemInfo.getDb4oConn(request);
		String searchFor = request.getParameter("searchFor");
		
		
		if (searchFor != null && searchFor.equals("thumbs")) {
			this.getThumbsBySearch(container, request, response);
			return;
		}
		
		
		if (searchFor != null && searchFor.equals("allCategorieAndKeyword")) {
			this.getAllCategorieAndKeywords(container, request, response);
			return;
		}
		
		if (searchFor != null && searchFor.equals("categories")) {
			this.getAllCategorie(container, request, response);
			return;
		}
		
		if (searchFor != null && searchFor.equals("prepare")) {
			ArrayList<DBCategory> categories = Db4oDaoGet.getAllCategories(container);
			request.setAttribute("categories", categories);
				
			ArrayList<DBKeyword> keywords = Db4oDaoGet.getAllKeywords(container);
			request.setAttribute("keywords", keywords);
			
			ArrayList<String> formats = Db4oDaoGet.getAllExifInfoByName(container, "format");
			request.setAttribute("formats", formats);
				
			ArrayList<String> exposureProgram = Db4oDaoGet.getAllExifInfoByName(container, "exposureProgram");
			request.setAttribute("exposureProgram", exposureProgram);
				
			ArrayList<String> exposureMode = Db4oDaoGet.getAllExifInfoByName(container, "exposureMode");
			request.setAttribute("exposureMode", exposureMode);
				
			ArrayList<String> exposureTime = Db4oDaoGet.getAllExifInfoByName(container, "exposureTime");
			request.setAttribute("exposureTime", exposureTime);
				
			ArrayList<String> colorSpace = Db4oDaoGet.getAllExifInfoByName(container, "colorSpace");
			request.setAttribute("colorSpace", colorSpace);
				
			ArrayList<String> fnumber = Db4oDaoGet.getAllExifInfoByName(container, "fnumber");
			request.setAttribute("fnumber", fnumber);
				
			ArrayList<String> makes = Db4oDaoGet.getAllExifInfoByName(container, "make");
			request.setAttribute("makes", makes);
				
			ArrayList<String> models = Db4oDaoGet.getAllExifInfoByName(container, "model");
			request.setAttribute("models", models);
			
			String url = response.encodeURL("/filter.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void getThumbsBySearch(ObjectContainer container,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		String in = request.getParameter("in");
		boolean furtherSearch = request.getParameter("furtherSearch") != null;
		
		ArrayList<DBPicInfo> photos 	= null;
		ArrayList<DBThumbInfo> thumbs 	= new ArrayList<DBThumbInfo>();
		
		if(in!=null && in.equals("search")) {
			SearchTerm tmp[][] = new SearchTerm[4][4];
			
			for(int i=0;i<4;i++) {
				for(int j=0;j<4;j++) {
					String name 	= request.getParameter("searchItemName" + i + j);
					String compare 	= request.getParameter("searchItemCompare" + i + j);
					String value	= request.getParameter("searchItemValue" + i + j);
					
					if(name!=null&&!name.equals("")&&value!=null&&!value.equals("")) {
						tmp[i][j] = new SearchTerm(name,compare,value);
						//System.out.println(name+compare+value);
					}
					else
						tmp[i][j] = null;
				}
			}
			
			
			photos = Db4oDaoGet.getPhotosByExtraSearch(container,tmp);
			
			for(int i = 0;i < photos.size();i++) {
				DBThumbInfo thumb = new DBThumbInfo(photos.get(i).getNr(),photos.get(i).getName());
				thumbs.add(thumb);
			}
			
			request.setAttribute("title", "Suche Ergebnisse");
			
			if(furtherSearch && lastSearchResult != null)
				thumbs = DBThumbInfo.intersect(thumbs, lastSearchResult);
			
			lastSearchResult = thumbs;
			
		}
		
		
		if(in!=null && in.equals("all")) {
			photos = Db4oDaoGet.getAllPhoto(container);
			
			for(int i = 0;i < photos.size();i++) {
				DBThumbInfo tmp = new DBThumbInfo(photos.get(i).getNr(),photos.get(i).getName());
				thumbs.add(tmp);
			}
			
			request.setAttribute("title", "Alle Thumbnails");
		}
		
		if (in != null && in.equals("category")) {
			int ktnr 	= Integer.parseInt(request.getParameter("ktnr"));
			String name	= request.getParameter("name");
			
			DBCategory category = new DBCategory(ktnr,name);
			
			photos = Db4oDaoGet.getPhotosByCategory(container, category);
			
			for(int i = 0;i < photos.size();i++) {
				DBThumbInfo tmp = new DBThumbInfo(photos.get(i).getNr(),photos.get(i).getName());
				thumbs.add(tmp);
			}
			
			request.setAttribute("title","Kategorie: " + name);
		}
		
		if(in != null && in.equals("keyword")) {
			int kwnr	= Integer.parseInt(request.getParameter("kwnr"));
			String word	= request.getParameter("word");
			
			DBKeyword keyword = new DBKeyword(kwnr,word);
			
			photos = Db4oDaoGet.getPhotosByKeyword(container,keyword);
			
			for(int i = 0;i < photos.size();i++) {
				DBThumbInfo tmp = new DBThumbInfo(photos.get(i).getNr(),photos.get(i).getName());
				thumbs.add(tmp);
			}
			
			request.setAttribute("title","Schlagwort: " + word);
		}
		
		
			
		request.setAttribute("Thumbs", thumbs);
		request.setAttribute("type", "thumbs");
		request.setAttribute("count", thumbs.size());
		String url = response.encodeURL("/showThumbs.jsp");
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	private void getAllCategorie(ObjectContainer container, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ArrayList<DBCategory> 	categories 	= Db4oDaoGet.getAllCategories(container);
		ArrayList<DBKeyword> 	keywords	= Db4oDaoGet.getAllKeywords(container);
		
		request.setAttribute("categories", categories);
		request.setAttribute("keywords", keywords);
		
		String url = response.encodeURL("/category.jsp");
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	private void getAllCategorieAndKeywords(ObjectContainer container,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ArrayList<DBKeyword> keywords = Db4oDaoGet.getAllKeywords(container);
		ArrayList<DBCategory> categories = Db4oDaoGet.getAllCategories(container);

		request.setAttribute("keywords", keywords);
		request.setAttribute("categories", categories);

		String url = response.encodeURL("/uploadImg.jsp");
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}
}
